const httpStatus = require('http-status');
const catchAsync = require('../utils/catchAsync');
const { searchHistoryService } = require('../services');
const logger = require('../utils/logger');

/**
 * 获取用户搜索历史
 */
const getUserSearchHistory = catchAsync(async (req, res) => {
  try {
    // 获取限制数量参数，默认为10
    const limit = req.query.limit ? parseInt(req.query.limit, 10) : 10;
    
    if (!req.user || (!req.user._id && !req.user.id)) {
      logger.warn('无法获取搜索历史: 用户未登录或ID不存在');
      return res.status(httpStatus.UNAUTHORIZED).send({
        error: 1,
        body: null,
        message: '需要登录才能获取搜索历史'
      });
    }

    // 确定用户ID - 支持多种格式
    const userId = req.user._id || req.user.id;
    
    logger.info(`获取用户(${userId})的搜索历史, 限制: ${limit}`);
    
    // 调用服务获取历史记录，限定类型为food
    const searchHistory = await searchHistoryService.getUserSearchHistory(userId, {
      limit,
      type: 'food'
    });
    
    // 格式化返回数据
    const formattedHistory = searchHistory.map(item => ({
      id: item._id,
      keyword: item.keyword,
      createdAt: item.createdAt
    }));
    
    logger.info(`成功获取用户搜索历史, 共${formattedHistory.length}条记录`);
    
    // 返回成功响应
    res.send({
      error: 0,
      body: {
        history: formattedHistory
      },
      message: ''
    });
  } catch (err) {
    logger.error(`获取搜索历史失败: ${err.message}`);
    if (err.stack) {
      logger.error(`错误堆栈: ${err.stack}`);
    }
    
    res.status(err.statusCode || httpStatus.INTERNAL_SERVER_ERROR).send({
      error: 1,
      body: null,
      message: err.message || '获取搜索历史失败'
    });
  }
});

/**
 * 清除用户搜索历史
 */
const clearSearchHistory = catchAsync(async (req, res) => {
  try {
    // 确定用户ID - 支持多种格式
    const userId = req.user._id || req.user.id;
    
    // 默认清除food类型的搜索历史
    const type = req.query.type || 'food';
    
    logger.info(`清除用户(${userId})的${type}类型搜索历史`);
    const result = await searchHistoryService.clearUserSearchHistory(userId, type);
    
    // 当前时间作为清除时间
    const clearedAt = new Date().toISOString();
    
    res.send({
      error: 0,
      body: {
        deletedCount: result.deletedCount,
        clearedAt: clearedAt
      },
      message: '搜索历史已清空'
    });
  } catch (err) {
    logger.error('清除搜索历史失败:', err);
    res.status(err.statusCode || httpStatus.INTERNAL_SERVER_ERROR).send({
      error: 1,
      body: null,
      message: err.message || '清除搜索历史失败'
    });
  }
});

module.exports = {
  getUserSearchHistory,
  clearSearchHistory,
}; 